#!/usr/bin/python2
# -*- coding: UTF-8 -*-

import logging
import urllib2
import urllib
import sys
import os
import re
import json
import codecs
import copy
import csv
import hashlib

def md5(content):
    m2 = hashlib.md5()
    m2.update(content)
    return m2.hexdigest()

def translate(content):
    appid = '20170604000052091'
    key = 'EpK8HLEzqqV3cNBk0A6M'
    salt = '1435660288'

    try:
        sign = md5(appid + content + salt + key)
        url = 'http://api.fanyi.baidu.com/api/trans/vip/translate?q=%s&from=zh&to=en&appid=%s&salt=%s&sign=%s' % (content, appid, salt, sign)
        response = urllib2.urlopen(url, timeout=5)
        html = response.read().decode('utf-8')
        result_json = json.loads(html)
        explains = result_json['trans_result'][0]['dst']
    except Exception, error:
        logging.error('translate (%s) failed: %s' % (content, error))
        return content

    return explains

def save(zh_en_list, id):
    csvfile = file('zh_to_en_' + str(id) + '.csv', 'wb')
    writer = csv.writer(csvfile)
    writer.writerow(['中文', '英文'])
    writer.writerows(zh_en_list)
    csvfile.close()

def main():
    key_file_path = "ch_key_list.txt"
    if not os.path.exists(key_file_path):
        logging.error('file %s is not exist')
        return

    zh_file = open(key_file_path, 'r')
    zh_list = zh_file.readlines()
    zh_file.close()

    id = 1
    zh_en_list = []
    for zh in zh_list:
        if zh[-1] == '\n':
            zh = zh[0:-1]

        if zh == '':
            continue

        try:
            zh_en_pair = (zh, translate(zh).encode(encoding='UTF-8', errors='strict'))
            zh_en_list.append(zh_en_pair)
        except Exception, error:
            logging.error('translate (%s) failed: %s' % (zh, error))
            zh_en_pair = (zh, '')
            zh_en_list.append(zh_en_pair)

        if len(zh_en_list) >= 1000:
            save(zh_en_list, id)
            id = id + 1
            zh_en_list = []

    save(zh_en_list, id)

if __name__ == '__main__':
    main()
else:
    pass